package cn.yogehaoren.limit;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.List;
import java.util.Vector;

/**
 * @author WangNing
 * @since 1.0
 */
public class LimitCustomerConsumer extends DefaultConsumer {
    private Channel channel;

    public LimitCustomerConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    private List<Long> eTagList = new Vector<>();

    /**
     *
     * @param consumerTag 消费标签
     * @param envelope 环境变量
     * @param properties properties
     * @param body 消息内容
     * @throws IOException 可能抛出的异常
     */
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

        System.out.println("------------- consumer message ---------------");
        System.out.println("consumerTag: " + consumerTag);
        System.out.println("envelope: " + envelope);
        System.out.println("properties: " + properties);
        System.out.println("body: " + new String(body));

        eTagList.add(envelope.getDeliveryTag());


    }

    public void  sendACK(){
        if(eTagList.size()>0){
            System.out.println("正在签收消息......");
            eTagList.forEach(e-> {
                try {
                    channel.basicAck(e, false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            });
            eTagList.clear();
            System.out.println("签收成功........");
        }

    }
}